library(tidyverse) # for graphing and data cleaning
library(googlesheets4) # for reading googlesheet data
library(lubridate) # for date manipulation
library(ggthemes) # for even more plotting themes
library(geofacet) # for special faceting with US map layout
gs4_deauth() # To not have to authorize each time you knit.
theme_set(theme_minimal()) # My favorite ggplot() theme :)
#Lisa's garden data
garden_harvest <- read_sheet("https://docs.google.com/spreadsheets/d/1DekSazCzKqPS2jnGhKue7tLxRU3GVL1oxi-4bEM5IWw/edit?usp=sharing") %>%
mutate(date = ymd(date))
# Seeds/plants (and other garden supply) costs
supply_costs <- read_sheet("https://docs.google.com/spreadsheets/d/1dPVHwZgR9BxpigbHLnA0U99TtVHHQtUzNB9UR0wvb7o/edit?usp=sharing",
col_types = "ccccnn")
# Planting dates and locations
plant_date_loc <- read_sheet("https://docs.google.com/spreadsheets/d/11YH0NtXQTncQbUse5wOsTtLSKAiNogjUA21jnX5Pnl4/edit?usp=sharing",
col_types = "cccnDlc")%>%
mutate(date = ymd(date))
# Tidy Tuesday data
kids <- readr::read_csv('https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2020/2020-09-15/kids.csv')
Before starting your assignment, you need to get yourself set up on GitHub and make sure GitHub is connected to R Studio. To do that, you should read the instruction (through the “Cloning a repo” section) and watch the video here. Then, do the following (if you get stuck on a step, don’t worry, I will help! You can always get started on the homework and we can figure out the GitHub piece later):
keep_md: TRUE in the YAML heading. The .md file is a markdown (NOT R Markdown) file that is an interim step to creating the html file. They are displayed fairly nicely in GitHub, so we want to keep it and look at it there. Click the boxes next to these two files, commit changes (remember to include a commit message), and push them (green up arrow).Put your name at the top of the document.
For ALL graphs, you should include appropriate labels.
Feel free to change the default theme, which I currently have set to theme_minimal().
Use good coding practice. Read the short sections on good code with pipes and ggplot2. This is part of your grade!
When you are finished with ALL the exercises, uncomment the options at the top so your document looks nicer. Don’t do it before then, or else you might miss some important warnings and messages.
These exercises will reiterate what you learned in the “Expanding the data wrangling toolkit” tutorial. If you haven’t gone through the tutorial yet, you should do that first.
garden_harvest data to find the total harvest weight in pounds for each vegetable and day of week. Display the results so that the vegetables are rows but the days of the week are columns.garden_harvest %>%
mutate(weight_lbs = weight / 453.59237,
day = weekdays(date)) %>%
group_by(vegetable, day) %>%
summarise(total_weight_lbs = sum(weight_lbs)) %>%
pivot_wider(id_cols = vegetable,
names_from = day,
values_from = total_weight_lbs,
values_fill = 0)
garden_harvest data to find the total harvest in pound for each vegetable variety and then try adding the plot variable from the plant_date_loc table. This will not turn out perfectly. What is the problem? How might you fix it?garden_harvest %>%
mutate(weight_lbs = weight / 453.59237) %>%
group_by(variety) %>%
summarise(total_weight_lbs = sum(weight_lbs)) %>%
left_join(plant_date_loc,
by = "variety")
Some varieties were planted in different plots but the total weight in pounds does not take that into account. To fix this, I’d join the data sets first, then find the total weight in pounds by each plot and variety.
garden_harvest and supply_cost datasets, along with data from somewhere like this to answer this question. You can answer this in words, referencing various join functions. You don’t need R code but could provide some if it’s helpful.You could join the data sets together so that the total weight in pounds and total cost of each variety of vegetable are together. Then you could create a variable for the cost per lbs x total weight of each vegetable in lbs from the prices on Whole Foods website. From there you could find the total cost of gardening and subtract the total cost at whole foods to determine how much you saved.
garden_harvest %>%
filter(vegetable == "tomatoes") %>%
group_by(variety) %>%
summarise(total_weight = (sum(weight))/453.59237) %>%
ggplot(aes(x = total_weight,
y = fct_rev(fct_relevel(variety, "volunteers", "Old German", "Amish Paste", "Black Krim", "Bonny Best", "Mortgage Lifter", "Brandywine", "Jet Star", "Cherokee Purple", "Better Boy", "Big Beef", "grape"))))+
geom_col() +
labs(title = "Total Harvest in Pounds",
x = "Variety of Tomato",
y = "Total Harvest Weight in lbs")
garden_harvest data, create two new variables: one that makes the varieties lowercase and another that finds the length of the variety name. Arrange the data by vegetable and length of variety name (smallest to largest), with one row for each vegetable variety. HINT: use str_to_lower(), str_length(), and distinct().garden_harvest %>%
group_by(vegetable, variety) %>%
distinct(variety) %>%
mutate(variety_lc = str_to_lower(variety),
variety_length = str_length(variety)) %>%
arrange(variety_length, vegetable)
garden_harvest data, find all distinct vegetable varieties that have “er” or “ar” in their name. HINT: str_detect() with an “or” statement (use the | for “or”) and distinct().garden_harvest %>%
distinct(variety) %>%
filter(str_detect(variety, c("ar"))|str_detect(variety, c("er")))
In this activity, you’ll examine some factors that may influence the use of bicycles in a bike-renting program. The data come from Washington, DC and cover the last quarter of 2014.
{300px}
{300px}
Two data tables are available:
Trips contains records of individual rentalsStations gives the locations of the bike rental stationsHere is the code to read in the data. We do this a little differently than usualy, which is why it is included here rather than at the top of this file. To avoid repeatedly re-reading the files, start the data import chunk with {r cache = TRUE} rather than the usual {r}.
data_site <-
"https://www.macalester.edu/~dshuman1/data/112/2014-Q4-Trips-History-Data.rds"
Trips <- readRDS(gzcon(url(data_site)))
Stations<-read_csv("http://www.macalester.edu/~dshuman1/data/112/DC-Stations.csv")
NOTE: The Trips data table is a random subset of 10,000 trips from the full quarterly data. Start with this small data table to develop your analysis commands. When you have this working well, you should access the full data set of more than 600,000 events by removing -Small from the name of the data_site.
It’s natural to expect that bikes are rented more at some times of day, some days of the week, some months of the year than others. The variable sdate gives the time (including the date) that the rental started. Make the following plots and interpret them:
sdate. Use geom_density().Trips %>%
ggplot(aes(x = sdate))+
geom_density() +
labs(title = "Density of Quartly Rentals",
y = "Frequency of Bike Rentals",
x = "Date")
This shows the how the number of rentals was spread out throughout the quarter. It clearly shows that as the months get colder, bike rentals slow.
mutate() with lubridate’s hour() and minute() functions to extract the hour of the day and minute within the hour from sdate. Hint: A minute is 1/60 of an hour, so create a variable where 3:30 is 3.5 and 3:45 is 3.75.Trips %>%
mutate(time_of_day = hour(sdate)+(minute(sdate)/60)) %>%
ggplot(aes(x = time_of_day))+
geom_density() +
labs(title = "Density of Daily Rentals",
y = "Frequency of Bike Rentals",
x = "Time")
This graph shows how rentals are spread out during the average day. There are clearly two peaks around 9am and 5:30pm, suggesting that many of the bike rentals are from people commuting to and from work.
Trips %>%
mutate(day = wday(sdate, label = TRUE)) %>%
ggplot(aes(y = day)) +
geom_bar()+
labs(title = "Daily Bike Rentals",
y = "Day of the Week",
x = "Bikes Rented")
More bikes are rented during the week than on the weekends. This further suggests that a majority of people using the bikes are commuting to and from work.
Trips %>%
mutate(time_of_day = hour(sdate)+(minute(sdate)/60),
day = wday(sdate, label = TRUE)) %>%
ggplot(aes(x = time_of_day))+
geom_density()+
facet_wrap(vars(day))+
labs(title = "Density of Daily Rentals by Day of the Week",
y = "Density of Bike Rentals",
x = "Time of Day")
On the weekdays, the graphs have two distinct peaks in the morning and late afternoon, but on the weekends there is a single peak at midday/early afternoon. This suggests that on the weekends most bike rentals are used for tourist/leisurely purposes, whereas during the week they are used for commuting.
The variable client describes whether the renter is a regular user (level Registered) or has not joined the bike-rental organization (Causal). The next set of exercises investigate whether these two different categories of users show different rental behavior and how client interacts with the patterns you found in the previous exercises. Repeat the graphic from Exercise @ref(exr:exr-temp) (d) with the following changes:
fill aesthetic for geom_density() to the client variable. You should also set alpha = .5 for transparency and color=NA to suppress the outline of the density function.Trips %>%
mutate(time_of_day = hour(sdate)+(minute(sdate)/60),
day = wday(sdate, label = TRUE)) %>%
ggplot(aes(x = time_of_day))+
geom_density(aes(fill = client, alpha = .5))+
facet_wrap(vars(day))+
labs(title = "Density of Daily Rentals by Day of the Week",
y = "Density of Bike Rentals",
x = "Time of Day")
This graph suggests that, during the week, most commuters are registered renters, whereas the leisurely riders are more likely causal renters, as the registered graphs have the distinct peaks on the weekdays, where the casual graph does not.
position = position_stack() to geom_density(). In your opinion, is this better or worse in terms of telling a story? What are the advantages/disadvantages of each?Trips %>%
mutate(time_of_day = hour(sdate)+(minute(sdate)/60),
day = wday(sdate, label = TRUE)) %>%
ggplot(aes(x = time_of_day))+
geom_density(aes(fill = client, alpha = .5),
position = position_stack())+
facet_wrap(vars(day)) +
labs(title = "Density of Daily Rentals by Day of the Week",
y = "Density of Bike Rentals",
x = "Time of Day")
While I think it is useful in telling an overall story as it shows the total density and how the two variables divide it up, I don’t think it is as effective when comparing the two variables because they are stacked on top of each other. For example, when the graphs aren’t stacked you can clearly see that during the week registered riders have two peaks around 9am and 5pm suggesting they are commuting to work, whereas casual riders have a single peak around midday.
weekend which will be “weekend” if the day is Saturday or Sunday and “weekday” otherwise (HINT: use the ifelse() function and the wday() function from lubridate). Then, update the graph from the previous problem by faceting on the new weekend variable.Trips %>%
mutate(time_of_day = hour(sdate)+(minute(sdate)/60),
day = wday(sdate, label = TRUE),
weekend = ifelse(day == c("Sat", "Sun"),
"Weekend",
"Weekday")) %>%
ggplot(aes(x = time_of_day))+
geom_density(aes(fill = client, alpha = .5))+
facet_wrap(vars(weekend)) +
labs(title = "Density of Daily Rentals",
y = "Density of Bike Rentals",
x = "Time of Day")
This graph shows that at the peak of rentals during the weekdays more registered users are riding than casual users. On the weekend its the opposite, where there are more casual casual useres than registered.
client and fill with weekday. What information does this graph tell you that the previous didn’t? Is one graph better than the other?Trips %>%
mutate(time_of_day = hour(sdate)+(minute(sdate)/60),
day = wday(sdate, label = TRUE),
weekend = ifelse(day == c("Sat", "Sun"),
"Weekend",
"Weekday")) %>%
ggplot(aes(x = time_of_day))+
geom_density(aes(fill = weekend, alpha = .5))+
facet_wrap(vars(client)) +
labs(title = "Density of Daily Rentals",
y = "Density of Bike Rentals",
x = "Time of Day")
Graph shows that casual ridership is lower during the week compared to the weekend. Registered ridership is the opposite, higher during the week and lower on the weekends. This suggests that casual riders tend to be from out of town or are tourists visiting the city on the weekends.
Stations to make a visualization of the total number of departures from each station in the Trips data. Use either color or size to show the variation in number of departures. We will improve this plot next week when we learn about maps!Trips %>%
left_join(Stations, c("sstation" = "name")) %>%
group_by(sstation) %>%
mutate(total_dep = n()) %>%
ggplot(aes(x = long, y = lat, size = total_dep))+
geom_jitter(alpha = .2)+
labs(title = "Total Number of Departures from each Station Location",
y = "Latitude",
x = "Longitude")
This graph allows us to visualize where these rentals are happening. This shows that most rentals are happening near downtown D.C.
Trips %>%
left_join(Stations, c("sstation" = "name")) %>%
group_by(client) %>%
mutate(percent_casual = mean(client == "Casual")) %>%
ggplot(aes(x = long, y = lat, color = percent_casual))+
geom_jitter(alpha = .2) +
scale_color_gradient(low = "green", high = "blue") +
labs(title = "Total Number of Departures from each Station Location",
y = "Latitude",
x = "Longitude")
This graph allows us to track the total number of rentals by type of client throughout the city. If I had to guess, the dots with the highest percent casual are probably located at touristy hotspots on the National Mall like the Lincoln Memorial or Washington Monument.
as_date(sdate) converts sdate from date-time format to date format.Trips %>%
mutate(ymd = as_date(sdate)) %>%
group_by(ymd, sstation) %>%
summarise(n = n()) %>% #I got a lot of help from my group on this one
arrange(desc(n)) %>%
head(10) -> top_ten_trips
top_ten_trips
top_ten_trips %>%
left_join(Trips, by = "sstation")
top_ten_trips %>%
left_join(Trips, by = "sstation") %>%
mutate(day = wday(sdate, label = TRUE)) %>%
group_by(client) %>%
mutate(total_dep_client = n())%>%
group_by(day, client) %>%
mutate(total_per_day = n()) %>%
summarise(prop_7dayclient = total_per_day/total_dep_client) %>%
distinct(prop_7dayclient) %>%
ggplot(aes(x = day,
y = prop_7dayclient)) +
geom_col() +
facet_wrap(vars(client)) +
labs(title = "Proportions of Departures by each Day and Client",
y = "Proportion of 7 Day Total",
x = "Day of the Week")
Casual riders ride much more often on the weekends, where registered riders ride much more often on the weekdays. This once again suggests that most registered riders are local commuters, whereas most casual riders are out of town tourists.
DID YOU REMEMBER TO GO BACK AND CHANGE THIS SET OF EXERCISES TO THE LARGER DATASET? IF NOT, DO THAT NOW.
This problem uses the data from the Tidy Tuesday competition this week, kids. If you need to refresh your memory on the data, read about it here.
facet_geo(). The graphic won’t load below since it came from a location on my computer. So, you’ll have to reference the original html on the moodle page to see it.kids %>%
filter(variable == "lib",
year == c("1997") | year == c("2016")) %>%
ggplot(aes(x = year,
y = inf_adj_perchild)) +
geom_line()+
facet_geo(vars(state))+
geom_text(aes(label=round(inf_adj_perchild, digits = 3)),
size = 3) +
theme(legend.position = "none",
plot.background = element_rect("steelblue"),
panel.grid = element_blank(),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank())+
labs(title = "Change in Public Spending on Libraries from 1997 to 2016",
subtitle = "Thousands of Dollars Spent per Child, adjusted for inflation")
DID YOU REMEMBER TO UNCOMMENT THE OPTIONS AT THE TOP?